﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.Utils.Menu;
using MMS.DAO;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using MMS.Validation;

namespace MMS
{
    public partial class FormRentMaterial : Form
    {
        private List<ViewMaterialDTO> order = new List<ViewMaterialDTO>();
        private ViewMaterialDAO viewMaterialDAO = new ViewMaterialDAO(Param.ConnectionString.Value);
        private OrderFormDTO orderFormDTO = new OrderFormDTO();
        ViewMaterialDTO viewMaterial = new ViewMaterialDTO();
        private OrderFormDAO orderFormDAO = new OrderFormDAO(Param.ConnectionString.Value);
        bool UIHasError = false;
        public FormRentMaterial()
        {
            InitializeComponent();
            this.Text = Utils.APP_TITLE;
        }

        private void FormRentMaterial_Load(object sender, EventArgs e)
        {
            gvMaterialList.OptionsBehavior.AutoPopulateColumns = false;
            gvMaterialList.OptionsBehavior.Editable = false;
            gvMaterialList.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            gvMaterialList.OptionsSelection.MultiSelect = false;
            gvMaterialList.OptionsSelection.EnableAppearanceFocusedCell = false;
            gvMaterialList.OptionsFind.AllowFindPanel = true;
            gvMaterialList.OptionsFind.AlwaysVisible = true;
            gvMaterialList.OptionsView.ShowGroupPanel = false;
            gvMaterialList.OptionsCustomization.AllowGroup = false;
            gvMaterialList.OptionsView.ShowIndicator = false;
            gvMaterialList.OptionsView.ShowAutoFilterRow = true;
            gvMaterialList.OptionsView.EnableAppearanceEvenRow = true;
            gvOrder.OptionsBehavior.AutoPopulateColumns = false;
            gvOrder_PricePerDay.OptionsColumn.AllowEdit = false;
            dtCreateDate.EditValue = DateTime.Today;
            dtRentDate.EditValue = DateTime.Today;
            //hide unused control
            label5.Visible = false;
            label4.Visible = false;
            label8.Visible = false;
            cbbVAT.Visible = false;
            txtDiscount.Visible = false;cbbVAT.SelectedIndex = 0;
            populateMaterialList();
            populateCustomerList();
            populateOrder();

        }

        //         private void bindUIToDevExValidation()
        //         {
        // 
        //             bindingSource2.DataSource = typeof(OrderFormDTO);
        //             bindingSource2.Add(orderFormDTO);
        // 
        //             // Specify the type of records stored in the BindingSource.
        //             //   bindingSource1.DataSource = typeof(List<ViewMaterialDTO>[]);
        //            // BindingList<ViewMaterialDTO> bList = new BindingList<ViewMaterialDTO>();
        // 
        //             // Bind the text editors to the MyRecord.FirstName and MyRecord.LastName properties.
        //             bindingSource1.DataSource = typeof(ViewMaterialDTO);
        //             bindingSource1.Add(viewMaterial);
        //           //  txtAddress.DataBindings.Add("EditValue", bList, "Address");
        // 
        //              txtAddress.DataBindings.Add(new Binding("EditValue", this.bindingSource1,
        //               "Address", true));
        //             txtBuilding.DataBindings.Add(new Binding("EditValue", this.bindingSource2,
        //              "Building", true));
        // 
        // 
        //             // Bind the DXErrorProvider to the data source.
        //             dxErrorProvider1.DataSource = bindingSource1;
        //             dxErrorProvider2.DataSource = bindingSource2;
        //             // Specify the container of controls (textEdit1 and textEdit2) 
        //             // which are monitored for errors.
        //             dxErrorProvider1.ContainerControl = this;
        //             dxErrorProvider2.ContainerControl = this;
        // 
        //         }

        private void populateOrder()
        {
            gcOrder.DataSource = order;
            gvOrder_MaterialId.FieldName = "MaterialId";
            gvOrder_MaterialName.FieldName = "MaterialName";
            gvOrder_Amount.FieldName = "Remaining";
            gvOrder_RentAmount.FieldName = "RentAmount";
            gvOrder_UnitName.FieldName = "UnitName";
            //gvOrder_Amount.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
            gvOrder_PricePerDay.FieldName = "PriceByDay";
            DevExpress.Utils.FormatInfo fi = new DevExpress.Utils.FormatInfo();
            fi.FormatType = DevExpress.Utils.FormatType.Numeric;
            fi.FormatString = "c0";
            gvOrder_PricePerDay.DisplayFormat.Assign(fi);
            gvOrder.BestFitColumns();
            //gvOrder_PricePerDay.DisplayFormat
        }

        private void populateMaterialList()
        {
            MaterialDAO materialDAO = new MaterialDAO(Param.ConnectionString.Value);
            List<MaterialDTO> materialList = new List<MaterialDTO>();
            materialList = materialDAO.SelectByRepository(Utils.Repository);
            gcMaterialList.DataSource = materialList;
            gvMaterialList_MaterialId.FieldName = "Id";
            gvMaterialList_MaterialName.FieldName = "Name";
            gvMaterialList_Remaining.FieldName = "Remaining";
            gvMaterialList.BestFitColumns();
        }

        private void populateCustomerList()
        {
            CustomerDAO customerDAO = new CustomerDAO(Param.ConnectionString.Value);
            List<CustomerDTO> customerList = new List<CustomerDTO>();
            customerList = customerDAO.SelectAll();
            lueCustomer.Properties.DataSource = customerList;
            lueCustomer.Properties.DisplayMember = "Name";
            lueCustomer.Properties.ValueMember = "Id";
            lueCustomer.Properties.Columns[0].FieldName = "Id";
            lueCustomer.Properties.Columns[1].FieldName = "Name";
            lueCustomer.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
            lueCustomer.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;
            lueCustomer.Properties.AutoSearchColumnIndex = 1;
        }

        private void lueCustomer_EditValueChanged(object sender, EventArgs e)
        {
            CustomerDTO cus = ((CustomerDTO)lueCustomer.GetSelectedDataRow());
            if (cus != null)
            {
                txtAddress.Text = cus.Address;
            }
        }

        private void gvMaterialList_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            Point pt = view.GridControl.PointToClient(Control.MousePosition);
            GridHitInfo info = view.CalcHitInfo(pt);
            if (info.InRow || info.InRowCell)
            {
                string materialId = ((MaterialDTO)gvMaterialList.GetRow(info.RowHandle)).Id;
                addMaterialToOrder(materialId);
            }

        }

        private void addMaterialToOrder(string materialId)
        {
            ViewMaterialDTO m = viewMaterialDAO.SelectByRepositoryAndMaterial(Utils.Repository, materialId);
            //Check this material exist in material list or not
            foreach (ViewMaterialDTO vm in order)
            {
                if (vm.MaterialId.Equals(m.MaterialId))
                {
                    return;
                }
            }
            order.Add(m);
            gvOrder.RefreshData();
            gvOrder.BestFitColumns();
        }

        private void gvOrder_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (order.Count > 0)
            {
                int remaining = (int)gvOrder.GetRowCellValue(e.RowHandle, "Remaining");
                int rentAmount = (int)gvOrder.GetRowCellValue(e.RowHandle, "RentAmount");
                if (rentAmount > remaining)
                {
                    e.Valid = false;
                    gvOrder.SetColumnError(gvOrder_RentAmount, "Số lượng thuê không được lớn hơn số lượng có trong kho");
                }    
            }
            else
            {
                e.Valid = true;}

        }

        private void gvOrder_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void gvOrder_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")
            {
                e.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void barButtonItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string itemName = e.Item.Name;
            if (itemName.Equals(bbiExit.Name))
            {
                this.Close();
            }
            else if (!UIHasError && !ValidateFormRentMaterial.isEmptyCustomer(this))
            {
                if (itemName.Equals(bbiSave.Name))
                {
                    if (!gvOrder.UpdateCurrentRow())
                    {
                        return;
                    }
                    string orderId = saveOrder();
                    saveOrderDetail(orderId);
                    clearAll();
                    populateMaterialList();
                }
                else if (itemName.Equals(bbiSaveAndPrint.Name))
                {
                    if (!gvOrder.UpdateCurrentRow())
                    {
                        return;
                    }
                    string orderId = saveOrder();
                    saveOrderDetail(orderId);
                }
            }
            else
            {
                lbErrorString.ForeColor = Color.Red;
                lbErrorString.Text = MessageBundle.ERROR_UI.Value;
                Utils.startTimer(timer1);
            }
        }

        private void clearAll()
        {
            lueCustomer.EditValue = null;
            order.Clear();
            gvOrder.RefreshData();
            txtAddress.Text = "";
            txtBuilding.Text = "";
        }

        private void saveOrderDetail(string orderId)
        {
            OrderForm_MaterialDAO orderMaterialDAO = new OrderForm_MaterialDAO(Param.ConnectionString.Value);
            Repository_MaterialDAO repository_MaterialDAO = new Repository_MaterialDAO(Param.ConnectionString.Value);
            foreach (ViewMaterialDTO vm in order)
            {
                if (vm.RentAmount <= 0)
                {
                    continue;
                }
                OrderForm_MaterialDTO orderMaterialDTO = new OrderForm_MaterialDTO();
                orderMaterialDTO.Amount = vm.RentAmount;
                orderMaterialDTO.Remaining = vm.RentAmount;
                orderMaterialDTO.IdMaterial = vm.MaterialId;
                orderMaterialDTO.IdOrderForm = orderId;
                orderMaterialDTO.IdRepository = vm.RepositoryId;
                orderMaterialDTO.IdType = 1;
                orderMaterialDTO.PriceByDay = vm.PriceByDay;
                orderMaterialDTO.RentDay = (DateTime)dtRentDate.EditValue;
                orderMaterialDTO.ReturnDay = DateTime.Today;
                orderMaterialDTO.TypeName = "Mượn";
                orderMaterialDAO.Insert(orderMaterialDTO);
                //Giam so luong vat tu hien con trong kho
                repository_MaterialDAO.AdjustRemainingAmount(vm.RepositoryId, vm.MaterialId, -vm.RentAmount);
            }
        }

        private string saveOrder()
        {

            orderFormDTO.Id = "";
            orderFormDTO.IdCustomer = ((CustomerDTO)lueCustomer.GetSelectedDataRow()).Id;
            orderFormDTO.Building = txtBuilding.Text;
            orderFormDTO.Vat = Int32.Parse(cbbVAT.Text.Split('%')[0]);
            if (txtDiscount.Text.Equals(""))
            {
                orderFormDTO.Discount = 0;
            }
            else
            {
                orderFormDTO.Discount = Int32.Parse(txtDiscount.Text);
            }
            return orderFormDAO.Insert2(orderFormDTO);

        }

        private void txtDiscount_KeyPress(object sender, KeyPressEventArgs e)
        {
            ValidateUtil.isDigit(e);

        }
        private void txtDiscount_EditValueChanged(object sender, EventArgs e)
        {

            if (!txtDiscount.EditValue.Equals(""))
            {
                int value = Int32.Parse(txtDiscount.EditValue.ToString());
                if (value > 100)
                {
                    UIHasError = true;
                    lbErrorString.ForeColor = Color.Red;
                    lbErrorString.Text = MessageBundle.ERROR_UI.Value;
                }
                else
                {
                    UIHasError = false;

                    lbErrorString.Text = "";
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            lbErrorString.Text = "";
        }

        private void gvMaterialList_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            if (e.MenuType == GridMenuType.Column)
            {
                List<DXMenuItem> itemList = new List<DXMenuItem>();
                foreach (DXMenuItem item in e.Menu.Items)
                {
                    if (item.Tag.Equals(GridStringId.MenuColumnGroupBox) || item.Tag.Equals((GridStringId.MenuColumnGroup)))
                    {
                        itemList.Add(item);
                    }
                }
                foreach (var dxMenuItem in itemList)
                {
                    e.Menu.Items.Remove(dxMenuItem);
                }
            }
            //if (!IsMenuAdded)
            //{
            //    DXMenuItem itemAdd = new DXMenuItem("Thêm vào đơn hàng");
            //    e.Menu.Items.Insert(0, itemAdd);
            //    IsMenuAdded = true;
            //}
        }
    }
}
